import React, { useState, useEffect } from 'react';
import { 
  Table, 
  Button, 
  Modal, 
  Form, 
  Input, 
  Select, 
  message, 
  Card,
  Tag,
  Space,
  Switch,
  Divider
} from 'antd';
import {
  PlusOutlined,
  EditOutlined,
  DeleteOutlined
} from '@ant-design/icons';
import './PermissionManagement.css';

const { Option } = Select;
const { Search } = Input;

const PermissionManagement = () => {
  const [permissions, setPermissions] = useState([]);
  const [filteredPermissions, setFilteredPermissions] = useState([]);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [editingPermission, setEditingPermission] = useState(null);
  const [loading, setLoading] = useState(false);
  const [searchText, setSearchText] = useState('');
  const [form] = Form.useForm();

  // 模拟权限数据
  useEffect(() => {
    const mockPermissions = [
      {
        id: 1,
        name: '用户管理',
        code: 'user:manage',
        type: '模块',
        description: '管理系统的用户信息',
        status: true,
        createTime: '2024-01-15 10:30:00'
      },
      {
        id: 2,
        name: '角色管理',
        code: 'role:manage',
        type: '模块',
        description: '管理系统角色和权限分配',
        status: true,
        createTime: '2024-01-15 11:20:00'
      },
      {
        id: 3,
        name: '文章查看',
        code: 'article:read',
        type: '操作',
        description: '查看文章内容',
        status: true,
        createTime: '2024-01-16 09:15:00'
      },
      {
        id: 4,
        name: '文章编辑',
        code: 'article:edit',
        type: '操作',
        description: '编辑文章内容',
        status: true,
        createTime: '2024-01-16 09:20:00'
      },
      {
        id: 5,
        name: '系统设置',
        code: 'system:settings',
        type: '模块',
        description: '管理系统配置参数',
        status: false,
        createTime: '2024-01-17 14:30:00'
      }
    ];
    setPermissions(mockPermissions);
    setFilteredPermissions(mockPermissions);
  }, []);

  // 搜索功能
  useEffect(() => {
    if (!searchText) {
      setFilteredPermissions(permissions);
    } else {
      const filtered = permissions.filter(permission =>
        permission.name.toLowerCase().includes(searchText.toLowerCase()) ||
        permission.code.toLowerCase().includes(searchText.toLowerCase()) ||
        permission.description.toLowerCase().includes(searchText.toLowerCase())
      );
      setFilteredPermissions(filtered);
    }
  }, [searchText, permissions]);

  const columns = [
    {
      title: '权限ID',
      dataIndex: 'id',
      key: 'id',
      width: 80,
      sorter: (a, b) => a.id - b.id,
    },
    {
      title: '权限名称',
      dataIndex: 'name',
      key: 'name',
      render: (text) => <span style={{ fontWeight: 500 }}>{text}</span>,
    },
    {
      title: '权限编码',
      dataIndex: 'code',
      key: 'code',
      render: (code) => <Tag color="blue">{code}</Tag>,
    },
    {
      title: '权限类型',
      dataIndex: 'type',
      key: 'type',
      render: (type) => {
        const typeMap = {
          '模块': { color: 'green' },
          '操作': { color: 'orange' },
          '菜单': { color: 'purple' }
        };
        const typeInfo = typeMap[type] || { color: 'default' };
        return <Tag color={typeInfo.color}>{type}</Tag>;
      },
      filters: [
        { text: '模块', value: '模块' },
        { text: '操作', value: '操作' },
        { text: '菜单', value: '菜单' }
      ],
      onFilter: (value, record) => record.type === value,
    },
    {
      title: '描述',
      dataIndex: 'description',
      key: 'description',
      ellipsis: true,
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status, record) => (
        <Switch
          checked={status}
          onChange={(checked) => handleStatusChange(record.id, checked)}
          checkedChildren="启用"
          unCheckedChildren="禁用"
        />
      ),
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      sorter: (a, b) => new Date(a.createTime) - new Date(b.createTime),
    },
    {
      title: '操作',
      key: 'action',
      width: 120,
      render: (_, record) => (
        <Space size="middle">
          <Button 
            type="primary" 
            icon={<EditOutlined />} 
            size="small"
            onClick={() => handleEdit(record)}
          >
            编辑
          </Button>
          <Button 
            danger 
            icon={<DeleteOutlined />} 
            size="small"
            onClick={() => handleDelete(record.id)}
          >
            删除
          </Button>
        </Space>
      ),
    },
  ];

  const handleAdd = () => {
    setEditingPermission(null);
    form.resetFields();
    setIsModalVisible(true);
  };

  const handleEdit = (record) => {
    setEditingPermission(record);
    form.setFieldsValue(record);
    setIsModalVisible(true);
  };

  const handleDelete = (id) => {
    Modal.confirm({
      title: '确认删除',
      content: '确定要删除这个权限吗？此操作不可恢复。',
      okText: '确认',
      cancelText: '取消',
      onOk: () => {
        setPermissions(permissions.filter(permission => permission.id !== id));
        message.success('权限删除成功');
      },
    });
  };

  const handleStatusChange = (id, status) => {
    setPermissions(permissions.map(permission =>
      permission.id === id ? { ...permission, status } : permission
    ));
    message.success(status ? '权限已启用' : '权限已禁用');
  };

  const handleOk = () => {
    form.validateFields().then(values => {
      setLoading(true);
      setTimeout(() => {
        if (editingPermission) {
          // 编辑权限
          const updatedPermissions = permissions.map(permission =>
            permission.id === editingPermission.id ? { ...values, id: editingPermission.id } : permission
          );
          setPermissions(updatedPermissions);
          message.success('权限更新成功');
        } else {
          // 添加新权限
          const newPermission = {
            ...values,
            id: Math.max(...permissions.map(p => p.id)) + 1,
            createTime: new Date().toLocaleString('zh-CN'),
            status: true
          };
          setPermissions([...permissions, newPermission]);
          message.success('权限添加成功');
        }
        setIsModalVisible(false);
        form.resetFields();
        setLoading(false);
      }, 1000);
    });
  };

  const handleCancel = () => {
    setIsModalVisible(false);
    form.resetFields();
  };

  return (
    <div className="permission-management">
      <Card>
        <div className="permission-header">
          <h2>权限管理</h2>
          <div className="permission-actions">
            <Search
              placeholder="搜索权限名称、编码或描述"
              allowClear
              value={searchText}
              onChange={(e) => setSearchText(e.target.value)}
              style={{ width: 300, marginRight: 16 }}
            />
            <Button 
              type="primary" 
              icon={<PlusOutlined />}
              onClick={handleAdd}
            >
              添加权限
            </Button>
          </div>
        </div>

        <Divider />

        <Table 
          columns={columns} 
          dataSource={filteredPermissions} 
          rowKey="id"
          pagination={{
            total: filteredPermissions.length,
            pageSize: 10,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条，共 ${total} 条记录`
          }}
          scroll={{ x: 1000 }}
        />
      </Card>

      <Modal
        title={editingPermission ? '编辑权限' : '添加权限'}
        visible={isModalVisible}
        onOk={handleOk}
        onCancel={handleCancel}
        okText="确定"
        cancelText="取消"
        width={600}
        confirmLoading={loading}
      >
        <Form
          form={form}
          layout="vertical"
        >
          <Form.Item
            name="name"
            label="权限名称"
            rules={[{ required: true, message: '请输入权限名称' }]}
          >
            <Input placeholder="请输入权限名称" />
          </Form.Item>

          <Form.Item
            name="code"
            label="权限编码"
            rules={[
              { required: true, message: '请输入权限编码' },
              { pattern: /^[a-z]+:[a-z]+$/, message: '权限编码格式为: 模块:操作' }
            ]}
          >
            <Input placeholder="例如: user:manage" />
          </Form.Item>

          <Form.Item
            name="type"
            label="权限类型"
            rules={[{ required: true, message: '请选择权限类型' }]}
          >
            <Select placeholder="请选择权限类型">
              <Option value="模块">模块</Option>
              <Option value="操作">操作</Option>
              <Option value="菜单">菜单</Option>
            </Select>
          </Form.Item>

          <Form.Item
            name="description"
            label="权限描述"
            rules={[{ required: true, message: '请输入权限描述' }]}
          >
            <Input.TextArea 
              placeholder="请输入权限描述" 
              rows={3}
            />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default PermissionManagement;